import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'
import Element from 'element-ui'
// import 'element-ui/lib/theme-chalk/index.css'
import qs from 'qs'
import VuexStore from './store'
import './assets/icons/iconfont.css'
import '@/styles/index.scss'

import MessageBox from '@/system/components/messageBox'
import Loading from '@/system/components/loading/index'
import Print from 'vue-print-nb'
import { Drag, Drop } from 'vue-drag-drop'
import AssetFlowSend from '@/system/components/AssetFlowSend'
import hasPermi from '@/directives/hasPermi'
Vue.use(Element, {
	size: 'medium',
})
Vue.use(MessageBox)
Vue.use(Loading)
Vue.use(Print)
Vue.use(hasPermi)

// 拖放
Vue.component('drag', Drag)
Vue.component('drop', Drop)
Vue.component('assetFlowSend', AssetFlowSend)

import cellView from '@/system/pages/cellView.vue'
Vue.component('cellView', cellView)
import templatePage from '@/system/pages/customPage/templatePage'
Vue.component('templatePage', templatePage)
//codemirror编辑器引入
import VueCodeMirror from 'vue-codemirror'
import 'codemirror/lib/codemirror.css'
Vue.use(VueCodeMirror)
//dialog弹出框移动JS
import './directives/dialogDrag'

Vue.config.productionTip = false
// Vue.prototype.$message = Message
Vue.prototype.$http = axios
Vue.prototype.routerMap = []

import sysConfig from '@/config/sysConfig'
import '@/assets/custom-theme-green/index.css'
var localurl = window.location.href.split('jypw')[0] + 'jypw/'
if (localurl.indexOf('localhost') == -1) {
	Vue.prototype.api = localurl
} else {
	Vue.prototype.api = process.env.VUE_APP_BASE_API
}
Vue.prototype.sysConfig = sysConfig
Date.prototype.format = function(fmt) {
	var o = {
		'M+': this.getMonth() + 1, //月份
		'd+': this.getDate(), //日
		'h+': this.getHours(), //小时
		'm+': this.getMinutes(), //分
		's+': this.getSeconds(), //秒
		'q+': Math.floor((this.getMonth() + 3) / 3), //季度
		S: this.getMilliseconds(), //毫秒
	}
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
	for (var k in o) if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
	return fmt
}

Vue.prototype.myGet = function(service, toast) {
	return new Promise((resolve, reject) => {
		axios
			.get(Vue.prototype.api + service)
			.then(res => {
				if (res.data.code == 190) {
					//需要登录
					this.$router.push({
						path: '/login',
					})
					return false
				}
				if (res.data && res.data.success) {
					resolve(res)
					if (toast && service) {
						Vue.prototype.success('操作成功', res.data.msg)
					}
				} else {
					Vue.prototype.msg('操作失败', res.data.msg)
				}
			})
			.catch(res => {
				this.$router.push({
					path: '/login',
				})
				reject(res)
			})
	})
}

Vue.prototype.myPost = function(service, data, toast, type = 1) {
	return new Promise((resolve, reject) => {
		var config
		var params = qs.stringify(data, {
			allowDots: true,
		})
		switch (type) {
			case 1:
				config = {
					headers: {
						'Content-Type': 'application/json',
					},
				}
				break
			case 2:
				config = {
					headers: {
						'Content-Type': 'multipart/form-data',
					},
				}
				break
		}
		axios
			.post(Vue.prototype.api + service, params, config)
			.then(function(res) {
				var tempres = res
				if (tempres.data.code == 190) {
					//需要登录
					this.$router.push({
						path: '/login',
					})
					return false
				}
				if (tempres.data && tempres.data.success) {
					resolve(tempres)
					if (toast && service) {
						Vue.prototype.success('操作成功', tempres.data.msg)
					}
				} else {
					//失败的时候不能调用resolve，resolve只能在成功的时候调用 可以用reject 在then后面加一个catch方法就是reject
					resolve(tempres)
					if (toast) {
						Vue.prototype.msg('操作失败', tempres.data.msg)
					}
				}
			})
			.catch(tempres => {
				this.$router.push({
					path: '/login',
				})
				reject(tempres)
			})
	}).catch(function(err) {
		console.log(err)
	})
}

Vue.prototype.message = function(info, type = 0) {
	const types = ['info', 'success', 'warning', 'error']
	let temptype = 'info'

	if (type != null && typeof type == 'number') {
		if (parseInt(type) >= 0 && parseInt(type) < 4) temptype = types[parseInt(type)]
	}

	this.$message({
		showClose: true,
		message: info,
		type: temptype,
		duration: 3000,
	})
}

Vue.prototype.messageBox = function(info, title = '提示', confirmText = '确定', cancelText = '取消') {
	if (confirmText == null || confirmText == '') {
		confirmText = '确定'
	}
	if (cancelText == null || cancelText == '') {
		cancelText = '取消'
	}
	return new Promise(resolve => {
		this.$msgBox
			.showMsgBox({
				title: title,
				content: info,
				cancelBtnText: cancelText,
				confirmBtnText: confirmText,
				isShowInput: false,
			})
			.then(async val => {
				resolve(val)
			})
			.catch(err => {
				resolve(err)
			})
	})
}

Vue.prototype.messageInput = function(info, title = '提示', confirmText = '确定', cancelText = '取消') {
	if (confirmText == null || confirmText == '') {
		confirmText = '确定'
	}
	if (cancelText == null || cancelText == '') {
		cancelText = '取消'
	}
	return new Promise(resolve => {
		this.$msgBox
			.showMsgBox({
				title: title,
				content: info,
				cancelBtnText: cancelText,
				confirmBtnText: confirmText,
				isShowInput: true,
			})
			.then(async val => {
				resolve(val)
			})
			.catch(err => {
				resolve(err)
			})
	})
}

Vue.prototype.linkClick = function(item) {
	console.log(item)
	var reg = /t\d{1,}/
	var pt = item.path
	var match = pt.match(reg)

	if (match) {
		console.log(match[0])
		var id = match[0].substr(1)
		const routes = [
			{
				path: item.path,
				name: item.name,
				component: templatePage,
				props: true,
				meta: {
					title: item.title,
					keepAlive: false,
					funcId: item.funcId,
				},
				children: [],
			},
		]
		let routerExist = false
		this.routerMap.forEach(element => {
			if (element === routes[0].name) {
				routerExist = true
				return
			}
		})
		if (!routerExist) {
			this.routerMap.push(routes[0].name)
			this.$router.addRoutes(routes)
			this.$router.options.routes.push(routes[0])
		}
	} else {
		this.$router.options.routes.forEach((route, index) => {
			if (route.path == item.path) {
				this.$set(route.meta, 'title', item.title)
				this.$set(route.meta, 'funcId', item.funcId)
			}
		})
	}
	console.log(id)
	this.$set(item, 'params', { id: id })
	this.$router.push(item)
}

//使用Vue.mixin的方法拦截了路由离开事件，并在该拦截方法中实现了销毁页面缓存的功能。
Vue.mixin({
	beforeRouteLeave: function(to, from, next) {
		// console.log(to)
		// console.log(from)

		//		console.log("路由守卫拦截路由"+ JSON.stringify(to));
		//      if (!from.meta.isKeep)
		//      {//此处判断是如果返回上一层，你可以根据自己的业务更改此处的判断逻辑，酌情决定是否摧毁本层缓存。
		//          if (this.$vnode && this.$vnode.data.keepAlive)
		//          {
		//              if (this.$vnode.parent && this.$vnode.parent.componentInstance && this.$vnode.parent.componentInstance.cache)
		//              {
		//                  if (this.$vnode.componentOptions)
		//                  {
		//                      var key = this.$vnode.key == null
		//                                  ? this.$vnode.componentOptions.Ctor.cid + (this.$vnode.componentOptions.tag ? `::${this.$vnode.componentOptions.tag}` : '')
		//                                  : this.$vnode.key;
		//                      var cache = this.$vnode.parent.componentInstance.cache;
		//                      var keys  = this.$vnode.parent.componentInstance.keys;
		//                      if (cache[key])
		//                      {
		//                          if (keys.length) {
		//                              var index = keys.indexOf(key);
		//                              if (index > -1) {
		//                                  keys.splice(index, 1);
		//                              }
		//                          }
		//                          delete cache[key];
		//                      }
		//                  }
		//              }
		//          }
		//          this.$destroy();
		//      }
		next()
	},
})

const myvue = new Vue({
	render: h => h(App),
	router,
	store: VuexStore,
}).$mount('#app')

export { myvue }
